Imports SubSonic
Imports ClubStarterKit.Data
Imports ClubStarterKit.Web
Imports System.Linq


Partial Class Statistics_Team
    Inherits System.Web.UI.Page

    Private m_teamid As Integer = 0

    Private Property TeamID() As Integer
        Get
            If m_teamid = 0 Then
                m_teamid = CType(ViewState("TeamID"), Integer)
            End If

            Return m_teamid
        End Get
        Set(ByVal value As Integer)
            ViewState("TeamID") = value
        End Set
    End Property

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If IsPostBack = False Then

            Try
                TeamID = Integer.Parse(Request("teamid").ToString())
            Catch ex As Exception
                Response.Redirect("~/CricketStats/default.aspx")
            End Try

            Using db As New CricketBLL.CricketStatsDataContext(Settings.DatabaseConnectionString)
                'Bind Teams
                BindTeams(db)

                'Bind Batting stats for team
                BindBatting(db)

                'Bind bowling stats for team
                BindBowling(db)

                'Bind Team stats
                BindTeamStats(db)

                'Set captains in left top
                BindCaptainsAndPlayers(db)

            End Using

        End If
        If User.IsInRole("GameRecorder") Then
            IsGameRecorderOrAdmin = True
        Else
            If User.IsInRole("Administrators") Then
                IsGameRecorderOrAdmin = True
            Else
                IsGameRecorderOrAdmin = False
            End If
        End If
    End Sub


    Private Sub BindTeamStats(ByVal dbContext As CricketBLL.CricketStatsDataContext)

        Try
            Dim stats = From ts In dbContext.Matches _
                        Where ts.TeamId = TeamID _
                        Group By Team = ts.Team _
                        Into Won = Count(ts.Result = "Win"), _
                        Lost = Count(ts.Result = "Loose"), _
                        Drawn = Count(ts.Result = "Draw"), _
                        Played = Count(ts.Result <> ""), _
                        Points = Count(ts.Points)

            gvTeamStats.DataSource = stats
            gvTeamStats.DataBind()


        Catch ex As Exception

        End Try

    End Sub

    Private Sub BindCaptainsAndPlayers(ByVal dbContext As CricketBLL.CricketStatsDataContext)
        Try
            Dim capts = From c In dbContext.Teams _
                        Where c.TeamId = TeamID _
                        Select New With { _
                        .Captain = c.Player.PlayerName, _
                        .ViceCaptain = c.Player1.PlayerName}

            lvCaptains.DataSource = capts
            lvCaptains.DataBind()

            TeamNamelbl.Text = (From t In dbContext.Teams _
                                Where t.TeamId = TeamID _
                                Select t.TeamName).Single()

            'Bind Captains drop down...
            Dim players = From p In dbContext.Players _
                          Order By p.PlayerName Ascending _
                          Select p
            ddlCaptain.DataSource = players
            ddlCaptain.DataBind()
            ddlViceCaptain.DataSource = players
            ddlViceCaptain.DataBind()
            MembersDropDown.DataSource = players
            MembersDropDown.DataBind()

            ddlCaptain.SelectedIndex = ddlCaptain.Items.IndexOf(ddlCaptain.Items.FindByText(capts.Single().Captain))
            ddlViceCaptain.SelectedIndex = ddlViceCaptain.Items.IndexOf(ddlViceCaptain.Items.FindByText(capts.Single().ViceCaptain))

        Catch ex As Exception
            lblDebug.Text = ex.Message
        End Try
    End Sub

    ''' <summary>
    ''' Binds teams to drop down and sets selected value to TeamId from QueryString
    ''' </summary>
    ''' <param name="dbContext"></param>
    ''' <remarks></remarks>
    Private Sub BindTeams(ByVal dbContext As CricketBLL.CricketStatsDataContext)
        ddlTeams.DataSource = From t In dbContext.Teams _
                              Select t
        ddlTeams.DataBind()

        ddlTeams.SelectedIndex = ddlTeams.Items.IndexOf(ddlTeams.Items.FindByValue(TeamID.ToString()))
    End Sub

    Private Sub BindBatting(ByVal dbContext As CricketBLL.CricketStatsDataContext)
        Try

            Dim stats = From bt In dbContext.PlayerStats _
                               Where bt.Match.TeamId = TeamID _
                               Group By Player = bt.Player _
                               Into TotalRuns = Sum(bt.RunsScored), _
                               NOs = Count(bt.NotOut = True), _
                               DNBs = Count(bt.DNB = True), _
                               Mins = Sum(bt.MinutesInBat), _
                               Fours = Sum(bt.FoursHit), _
                               Sixes = Sum(bt.SixesHit) _
                               Order By Player.PlayerName _
                               Select Player, TotalRuns, Mins, Fours, Sixes, NOs, DNBs

            gvBatting.DataSource = stats
            gvBatting.DataBind()

        Catch ex As Exception

        End Try
    End Sub

    Private Sub BindBowling(ByVal dbContext As CricketBLL.CricketStatsDataContext)
        Try
            Dim stats = From bt In dbContext.PlayerStats _
                               Where bt.Match.TeamId = TeamID _
                               AndAlso bt.OversBowled > 0 _
                               Group By Player = bt.Player _
                               Into Runs = Sum(bt.Runs), _
                               Overs = Sum(bt.OversBowled), _
                               Maidens = Sum(bt.Maidens), _
                               Wickets = Sum(bt.Wickets), _
                               Catches = Sum(bt.Catches) _
                               Order By Player.PlayerName _
                               Select Player, Runs, Overs, Maidens, Wickets, Catches

            gvBowling.DataSource = stats
            gvBowling.DataBind()

        Catch ex As Exception
            lblDebug.Text = ex.Message
        End Try
    End Sub

    Private m_isallowed As Boolean = False
    Public Property IsGameRecorderOrAdmin() As Boolean
        Get
            Return m_isallowed
        End Get
        Set(ByVal value As Boolean)
            m_isallowed = value
        End Set
    End Property

    Protected Sub SeasonsDropDown_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlTeams.SelectedIndexChanged

        'Dim value As String = CType(sender, DropDownList).SelectedValue.ToString()
        'Response.Redirect("~/CricketStats/team.aspx?teamid=" & value)

        TeamID = Integer.Parse(ddlTeams.SelectedValue)

        Using db As New CricketBLL.CricketStatsDataContext(Settings.DatabaseConnectionString)

            'Bind Batting stats for team
            BindBatting(db)

            'Bind bowling stats for team
            BindBowling(db)

            'Bind Team stats
            BindTeamStats(db)

            'Set captains in left top
            BindCaptainsAndPlayers(db)
        End Using

    End Sub

    Protected Sub AddPlayer_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles AddPlayer.Click

        'ClubStarterKit.Web.League.AddPlayerToTeam(MembersDropDown.SelectedValue, Request("teamid"))
        MsgBox("Player has been added. PLEASE do not try to add this person again. Their stats will not show up in the Team page until statistics for the player has been added.", MsgBoxStyle.Information, "ClubStarterKit - Player Added")
        'Response.Redirect("~/CricketStats/team.aspx?teamid=" & Request("teamid"))

    End Sub

    Protected Sub lBtnUpdateCaptains_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lBtnUpdateCaptains.Click
        Try
            Dim div As HtmlControl = Me.FindControl("leftblock")


            Using db As New CricketBLL.CricketStatsDataContext(Settings.DatabaseConnectionString)

                'Update capts...
                Dim capts = (From c In db.Teams _
                            Where c.TeamId = TeamID _
                            Select c).Single()

                If capts.ViceCaptainId <> Integer.Parse(ddlViceCaptain.SelectedValue) Or _
                    capts.CaptainId <> Integer.Parse(ddlCaptain.SelectedValue) Then

                    capts.CaptainId = Integer.Parse(ddlCaptain.SelectedValue)
                    capts.ViceCaptainId = Integer.Parse(ddlViceCaptain.SelectedValue)

                    db.SubmitChanges()

                    'Set captains in left top
                    BindCaptainsAndPlayers(db)
                End If
            End Using
        Catch ex As Exception

        End Try
    End Sub
End Class
